package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.up.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.enums.FileTypeEnum;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.IamFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.up.ReportProblemMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.up.ReportProblem;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.up.ReportProblemService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by ${yangsy} on 2017/4/20.
 */
public class ReportProblemServiceImpl implements ReportProblemService {

    @Autowired
    private ReportProblemMapper reportProblemMapper;
    @Autowired
    private IamFileMapper iamFileMapper;

    @Override
    public int insert(ReportProblem record, String uploadFiles, String deletedFiles) {
        //插入数据成功之后，返回的条数
        int resultCount = 0;
        //保存业务数据
        resultCount = reportProblemMapper.insertSelective(record);
        //更新的附件不为空的情况
        if (uploadFiles != null && !uploadFiles.equals("")) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                //重新设置附件属性
                String pId = record.getProblemId();
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    //设置主键
                    _file.setFileId(UniqueUtil.uuid());
                    //设置业务数据id
                    _file.setBusinessId(pId);
                    _file.setFileType(FileTypeEnum.getCode(_file.getExt()));
                }
                resultCount += iamFileMapper.insert(listFiles);
            }
        }
        return resultCount;
    }

    @Override
    public JSONObject list(ReportProblem reportProblem) {
        JSONObject jsonObject = new JSONObject();
        reportProblem.setLimit(reportProblem.getLimit() == null ? 10 : reportProblem.getLimit());
        reportProblem.setOffset(reportProblem.getOffset() == null ? 0 : reportProblem.getOffset());
        jsonObject.put("total", reportProblemMapper.queryCount(reportProblem));
        jsonObject.put("rows", JSON.toJSON(reportProblemMapper.queryList(reportProblem)));
        return jsonObject;
    }

    @Override
    public ReportProblem selectByPrimaryKey(String problemId) {
        return reportProblemMapper.selectByPrimaryKey(problemId);
    }
}
